import { get_org_by_user, set_params } from '@/api/api.js'
import router from '@/router/index'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouterStore } from './router'
import { dictStore } from './dict'
import { sessionMemory } from '@/utils/sessionMemory'
export const useUserStore = defineStore('user', () => {
  // 退出登录 需要清除
  const isTopMenus = ref(sessionMemory.getItem('isTopMenus'))
  const userInfo = ref(sessionMemory.getItem('userInfo'))
  const orgInfo = ref(sessionMemory.getItem('orgInfo')) // level 1省级 2市级 3区县 4乡镇街道
  const roleInfo = ref(sessionMemory.getItem('roleInfo'))
  const token = ref(sessionMemory.getItem('token'))
  const userAreaArr = ref(sessionMemory.getItem('userAreaArr'))
  const userLastArea = ref(sessionMemory.getItem('userLastArea'))
  const userParentArea = ref(sessionMemory.getItem('userParentArea'))
  const fileUrl = ref(sessionMemory.getItem('fileUrl'))


  // 存储token
  const setToken = (val) => {
    token.value = val
    sessionMemory.setItem("token", token.value)
  }

  // 存储用户信息
  const setUser = val => {
    sessionMemory.setItem("userInfo", val)
    userInfo.value = val
  }

  // 获取机构信息
  const getOrgList = async () => {
    const res = await get_org_by_user()
    if (res.succeed) {
      return res.data
    }
  }

  // 当前用户选择进入的哪个机构 存储机构信息
  const setOrgInfo = val => {
    orgInfo.value = val
    sessionMemory.setItem("orgInfo", val)
    // 存储用户区划
    let userAreaArrKey = ['provinceCode', 'cityCode', 'countyCode', 'streetCode', 'communityCode']
    let areaArr = []
    userAreaArrKey.forEach(item => {
      val[item] && areaArr.push(val[item])
    })
    userAreaArr.value = areaArr
    let arr = areaArr.filter(item => item)
    userLastArea.value = arr[arr.length - 1]
    userParentArea.value = arr[arr.length - 2]
    sessionMemory.setItem('userAreaArr', areaArr)
    sessionMemory.setItem('userLastArea', arr[arr.length - 1])
    sessionMemory.setItem('userParentArea', arr[arr.length - 2])
  }

  // 处理登录后事件
  const handleLogin = async val => {
    // 存储当前用户下的机构信息
    setOrgInfo(val)
    // 存储字典
    let dictRes = await dictStore().getDict()
    // 获取待办事项
    // await appCurrentState().SET_WAIT_LIST()
    // 获取后台路由-存储路由
    let routerRes = await useRouterStore().SetAsyncRouter()
    if (routerRes) {
      useRouterStore().asyncRouters.allRoutes.forEach(asyncRouter => {
        router.addRoute(asyncRouter)
      })
      // 判断是否显示顶部菜单
      if (orgInfo.value.topMenu == 1) {
        // 有顶部菜单
        sessionMemory.setItem('isTopMenus', 1)
        isTopMenus.value = 1
        if (orgInfo.value.enterIndex == 1) {
          router.replace({ name: 'Home' })
        } else {
          await getDefaultMenu(useRouterStore().asyncRouters.leftRoutes)
        }
      } else {
        // 无顶部菜单
        sessionMemory.setItem('isTopMenus', 2)
        isTopMenus.value = 2
        if (orgInfo.value.enterIndex == 1) {
          router.replace({ name: 'Home' })
        } else {
          await getDefaultMenu(useRouterStore().asyncRouters.allRoutes)
        }
      }
      return true
    } else {
      return false
    }
  }

  const toLogin = async result => {
    // 存储用户信息
    setUser(result.data)
    // 获取机构列表
    let orgRes = {} || await getOrgList()
    // if (orgRes) {
      return await handleLogin(orgRes)
    // } 
  }

  const getDefaultMenu = async routes => {
    if (routes?.length > 0) {
      if (!routes[0].children || routes[0].children.length == 0 || routes[0].level == 4) {
        await router.replace({ name: routes[0].name })
      } else {
        // 递归找到默认菜单
        getDefaultMenu(routes[0].children)
      }
    }
  }

  /* 清理数据 */
  const ClearStorage = () => {
    sessionStorage.clear()
    // pinia数据清空
    isTopMenus.value = 1
    userInfo.value = {}
    orgInfo.value = {}
    roleInfo.value = {}
    token.value = ""
    userAreaArr.value = ""
    userLastArea.value = ""
    userParentArea.value = ""
    fileUrl.value = ""
    dictStore().clearDict()
    useRouterStore().clearRouter()
  }

  /* 登出*/
  const LoginOut = () => {
    ClearStorage()
    router.push({ name: 'Login', replace: true })
  }

  return {
    fileUrl,
    userInfo,
    userLastArea,
    userParentArea,
    userAreaArr,
    orgInfo,
    roleInfo,
    isTopMenus,
    token,
    LoginOut,
    setToken,
    handleLogin,
    ClearStorage,
    getDefaultMenu,
    setOrgInfo,
    toLogin
  }
})
